package com.ncbee.base.service.serviceimpl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ncbee.base.dao.RoleDao;
import com.ncbee.base.dao.RoleResourceDao;
import com.ncbee.base.model.entity.Role;
import com.ncbee.base.model.entity.RoleResource;
import com.ncbee.base.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author youdianyun
 * @since 2018-11-23
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleDao, Role> implements RoleService {
    @Autowired
    private RoleResourceDao resourceDao;

    /**
     * 1:删除角色原有资源
     * 2:新增角色新资源
     * @param roleId
     * @param resourceIds
     * @return
     */
    @Override
    @CacheEvict(value="userAllResource",allEntries = true)
    public boolean grantResourceToRole(Long roleId, String resourceIds) {
        int expectRow=0;
        int realRow=0;
        Map<String,Object> deleteParam=new HashMap();
        deleteParam.put("role_id",roleId);
        resourceDao.deleteByMap(deleteParam);
        List<Long> resourceIdList=null;
        if(!StringUtils.isEmpty(resourceIds)){
            resourceIdList= JSONArray.parseArray(resourceIds,Long.class);
            expectRow=resourceIdList.size();
        }
        List<RoleResource> roleResourceList=null;
        if(!CollectionUtils.isEmpty(resourceIdList)){
            roleResourceList=new ArrayList();
            for(Long resourceId:resourceIdList){
                RoleResource roleResource=new RoleResource();
                roleResource.setResourceId(resourceId);
                roleResource.setRoleId(roleId);
                roleResource.setCreateTime(LocalDateTime.now());
                roleResourceList.add(roleResource);
            }
            realRow=resourceDao.batchSave(roleResourceList);
        }
        return (expectRow==realRow);
    }
}
